package com.szl.group.config.auth.custom;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szl.group.common.enums.ResultCodeEnum;
import com.szl.group.common.model.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.web.session.InvalidSessionStrategy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：zhangC
 * @date ：Created in 2020/7/22 17:17
 * @description：session非法处理
 * @version: $2.0
 */
@Component
public class CustomInvalidSessionStrategy implements InvalidSessionStrategy {

    @Value("${spring.security.loginType}")
    private String loginType;

    @Resource
    private  ObjectMapper objectMapper ;

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException{
        // 自定义session无效处理
        if (loginType.equalsIgnoreCase("JSON")) {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(R.fail(ResultCodeEnum.TOKEN_EXPIRED, ResultCodeEnum.TOKEN_EXPIRED.getMessage())));
        } else {
            response.sendRedirect("/login.html");
        }
    }
}